package com.ruoyi.sales.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.sales.domain.SalesOrder;
import com.ruoyi.sales.service.ISalesOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.RoleUtils;
import com.ruoyi.sales.utils.OrderCodeGenerator;
import com.ruoyi.basedata.service.IBaseCustomerService;
import com.ruoyi.basedata.domain.BaseCustomer;
import com.ruoyi.basedata.service.IBaseProductService;
import com.ruoyi.basedata.domain.BaseProduct;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.api.service.IStockService;
import com.ruoyi.api.dto.StockInventoryDTO;

/**
 * 销售订单主Controller
 * 
 * @author ruoyi
 * @date 2025-06-17
 */
@Controller
@RequestMapping("/sales/order")
public class SalesOrderController extends BaseController
{
    private String prefix = "sales/order";

    @Autowired
    private ISalesOrderService salesOrderService;
    
    @Autowired
    private IBaseCustomerService baseCustomerService;
    
    @Autowired
    private IBaseProductService baseProductService;
    
    @Autowired(required = false)
    private IStockService stockService;

    @RequiresPermissions("sales:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    /**
     * 查询销售订单主列表
     */
    @RequiresPermissions("sales:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SalesOrder salesOrder)
    {
        // 设置当前登录用户名，用于数据权限控制
        Map<String, Object> params = new HashMap<>();
        params.put("loginName", ShiroUtils.getLoginName());
        
        // 判断是否为审核员
        boolean isAuditor = RoleUtils.isAuditor();
        params.put("isAuditor", isAuditor);
        
        // 判断是否为总负责人
        boolean isChief = RoleUtils.isChief();
        params.put("isChief", isChief);
        
        // 总负责人只能看到审核通过的数据
        if (isChief) {
            salesOrder.setAuditStatus("1"); // 审核通过
        }
        
        salesOrder.setParams(params);
        
        startPage();
        List<SalesOrder> list = salesOrderService.selectSalesOrderList(salesOrder);
        return getDataTable(list);
    }

    /**
     * 导出销售订单主列表
     */
    @RequiresPermissions("sales:order:export")
    @Log(title = "销售订单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SalesOrder salesOrder)
    {
        List<SalesOrder> list = salesOrderService.selectSalesOrderList(salesOrder);
        ExcelUtil<SalesOrder> util = new ExcelUtil<SalesOrder>(SalesOrder.class);
        return util.exportExcel(list, "销售订单主数据");
    }

    /**
     * 新增销售订单主
     */
    @RequiresPermissions("sales:order:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 自动生成订单编号
        String orderCode = OrderCodeGenerator.generateSalesOrderCode();
        mmap.put("orderCode", orderCode);
        
        // 查询所有可用的客户列表
        BaseCustomer baseCustomer = new BaseCustomer();
        baseCustomer.setStatus("0"); // 0表示正常状态的客户
        List<BaseCustomer> customerList = baseCustomerService.selectBaseCustomerList(baseCustomer);
        mmap.put("customerList", customerList);
        
        // 查询所有可用的产品列表
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态的产品
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        mmap.put("productList", productList);
        
        // 查询商品类别字典
        List<SysDictData> categoryList = DictUtils.getDictCache("product_category");
        mmap.put("categoryList", categoryList);
        
        // 将当前登录用户名添加到session中
        String loginName = ShiroUtils.getLoginName();
        getRequest().getSession().setAttribute("loginName", loginName);
        
        return prefix + "/add";
    }

    /**
     * 新增保存销售订单主
     */
    @RequiresPermissions("sales:order:add")
    @Log(title = "销售订单主", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SalesOrder salesOrder)
    {
        // 确保设置创建者和更新者
        String loginName = ShiroUtils.getLoginName();
        salesOrder.setCreatedBy(loginName);
        salesOrder.setUpdatedBy(loginName);
        return toAjax(salesOrderService.insertSalesOrder(salesOrder));
    }

    /**
     * 修改销售订单主
     */
    @RequiresPermissions("sales:order:edit")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        SalesOrder salesOrder = salesOrderService.selectSalesOrderByOrderId(orderId);
        mmap.put("salesOrder", salesOrder);
        
        // 查询所有可用的客户列表
        BaseCustomer baseCustomer = new BaseCustomer();
        baseCustomer.setStatus("0"); // 0表示正常状态的客户
        List<BaseCustomer> customerList = baseCustomerService.selectBaseCustomerList(baseCustomer);
        mmap.put("customerList", customerList);
        
        // 查询所有可用的产品列表
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态的产品
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        mmap.put("productList", productList);
        
        // 查询商品类别字典
        List<SysDictData> categoryList = DictUtils.getDictCache("product_category");
        mmap.put("categoryList", categoryList);
        
        // 将当前登录用户名添加到session中
        String loginName = ShiroUtils.getLoginName();
        getRequest().getSession().setAttribute("loginName", loginName);
        
        return prefix + "/edit";
    }

    /**
     * 修改保存销售订单主
     */
    @RequiresPermissions("sales:order:edit")
    @Log(title = "销售订单主", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SalesOrder salesOrder)
    {
        // 普通用户不能修改订单状态和审核状态
        SalesOrder existingOrder = salesOrderService.selectSalesOrderByOrderId(salesOrder.getOrderId());
        salesOrder.setOrderStatus(existingOrder.getOrderStatus());
        salesOrder.setAuditStatus(existingOrder.getAuditStatus());
        
        // 确保设置更新者
        String loginName = ShiroUtils.getLoginName();
        salesOrder.setUpdatedBy(loginName);
        
        return toAjax(salesOrderService.updateSalesOrder(salesOrder));
    }

    /**
     * 删除销售订单主
     */
    @RequiresPermissions("sales:order:remove")
    @Log(title = "销售订单主", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(salesOrderService.deleteSalesOrderByOrderIds(ids));
    }

    /**
     * 获取客户列表
     */
    @GetMapping("/customerList")
    @ResponseBody
    public AjaxResult getCustomerList()
    {
        BaseCustomer baseCustomer = new BaseCustomer();
        baseCustomer.setStatus("0"); // 0表示正常状态
        List<BaseCustomer> customerList = baseCustomerService.selectBaseCustomerList(baseCustomer);
        return AjaxResult.success(customerList);
    }
    
    /**
     * 获取产品列表
     */
    @GetMapping("/productList")
    @ResponseBody
    public AjaxResult getProductList()
    {
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setStatus("0"); // 0表示正常状态
        List<BaseProduct> productList = baseProductService.selectBaseProductList(baseProduct);
        return AjaxResult.success(productList);
    }
    
    /**
     * 检查商品库存是否充足
     */
    @PostMapping("/checkStock")
    @ResponseBody
    public AjaxResult checkStock(Long productId, Integer quantity)
    {
        if (stockService == null) {
            // 如果没有库存服务，默认库存充足
            return AjaxResult.success();
        }
        
        if (productId == null || quantity == null || quantity <= 0) {
            return AjaxResult.error("参数错误");
        }
        
        // 检查商品库存是否足够
        boolean isStockSufficient = stockService.checkStockSufficient(productId, quantity);
        
        if (isStockSufficient) {
            return AjaxResult.success();
        } else {
            // 获取当前库存信息，用于展示给用户
            StockInventoryDTO inventory = stockService.getInventoryByProductId(productId);
            Long currentQuantity = inventory != null ? inventory.getCurrentQuantity() : 0L;
            
            // 获取商品名称
            BaseProduct product = baseProductService.selectBaseProductByProductId(productId);
            String productName = product != null ? product.getProductName() : "未知商品";
            
            return AjaxResult.error(String.format("商品【%s】库存不足，当前库存: %d，需要: %d", 
                productName, currentQuantity, quantity));
        }
    }
}
